from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework.validators import UniqueValidator
from apps.teachers.models import Teacher


class CreateUserSerializer(ModelSerializer):
    """用户注册的序列化器"""

    # 添加 "确认密码" 字段
    repassword = serializers.CharField(label="确认密码", write_only=True)

    class Meta:
        model = Teacher
        fields = ('username', 'password', 'repassword')
        # 为字段添加约束
        extra_kwargs = {
            "username": {
                "validators": [
                    UniqueValidator(
                        queryset=Teacher.objects.all(),
                        message="该用户名已存在, 请选择其他用户名!"
                    )
                ],
                "min_length": 6,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许6-20个字符的用户名",
                    "max_length": "仅允许6-20个字符的用户名",
                }
            },
            "password": {
                "write_only": True,
                "min_length": 6,
                "max_length": 15,
                "error_messages": {
                    "min_length": "仅允许6-15个字符的密码",
                    "max_length": "仅允许6-15个字符的密码",
                }
            }
        }

    def validate(self, attrs):
        # 确认密码校验
        if attrs["password"] != attrs["repassword"]:
            raise serializers.ValidationError('两次密码不一致')

        return attrs

    def create(self, validated_data):
        """创建用户"""
        # 清除Teacher模型中不存在的字段(写入不存在的字段会报错)
        del validated_data["repassword"]
        # 填充 nickname 字段
        validated_data["nickname"] = validated_data["username"]

        user = super().create(validated_data)
        # 对明文密码进行加密写入数据库
        user.set_password(validated_data['password'])
        user.save()

        return user


class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        exclude = ('password', 'is_active')


class UpdateUserBaseInfoSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        fields = ('username', 'nickname', 'name', 'telephone', 'email')

        # 为字段添加约束
        extra_kwargs = {
            "username": {
                "read_only": True,
            }
        }


class UpdateUserPasswordSerializer(serializers.Serializer):
    old_pwd = serializers.CharField(label="原密码", write_only=True, min_length=6, max_length=15)
    new_pwd = serializers.CharField(label='新密码', write_only=True, min_length=6, max_length=15)
    re_pwd = serializers.CharField(label='确认新密码', write_only=True, min_length=6, max_length=15)

    def validate_old_pwd(self, value):
        instance = self.instance
        if not instance.check_password(value):
            raise serializers.ValidationError('原密码错误, 请输入正确的密码！')
        return value

    def validate(self, attrs):
        if attrs["new_pwd"] != attrs["re_pwd"]:
            raise serializers.ValidationError('两次密码不一致！')
        return attrs

    def update(self, instance, validated_data):
        new_password = validated_data['new_pwd']
        instance.set_password(new_password)
        instance.save()
        return instance

    def create(self, validated_data):
        pass
